<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    width="30%"
    class="wechat-dialog">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px">
      <el-form-item label="客服名称" prop="name">
        <mt-input v-model="form.name" :width="inputWidth"></mt-input>
      </el-form-item>
      <el-form-item label="客服头像">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <mt-button @click="handleSubmitBtn">确定</mt-button>
      <mt-button type="submain" @click="handleClose">取消</mt-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: "WechatDialog",

  data () {
    return {
      form: {
        name: "",
        imageUrl: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入客服账号名称", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ]
      },
      dialogType: "add",
      dialogVisible: false,
      inputWidth: "calc(100% - 1rem)"
    };
  },

  computed: {
    title () {
      if (this.dialogType === "add") return "新建客服";
      else if (this.dialogType === "edit") return "编辑客服";
    }
  },

  created () {
  },

  mounted () {},

  methods: {
    /* 触发弹窗 */
    open (type = "add", item = {}) {
      this._.assign(this.form, item);
      this.dialogType = type;
      this.dialogVisible = true;
    },

    /* 上传文件 */
    beforeAvatarUpload () {},

    /* 提交 */
    handleSubmitBtn () {
      // 校验
      this.$refs["form"].validate(valid => {
        if (valid) this.handleSubmit();
        else return false;
      });
    },
    handleSubmit () {
      if (this.dialogType === "add") {
        this.$mtMessage.success("新增成功！");
      }
      else if (this.dialogType === "edit") {
        this.$mtMessage.success("修改成功！");
      }
      this.handleClose();
      this.$emit("update");
    },

    /* 关闭弹窗 */
    handleClose () {
      this.$refs["form"].resetFields();
      this.dialogVisible = false;
    }
  }
};
</script>

<style lang="scss">
.wechat-dialog {
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
    }
    &:hover {
      border-color: #409EFF;
    }
  }
}
</style>
